package com.codefish.codefish_blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codefish.codefish_blog.entity.User;
import com.codefish.codefish_blog.mapper.UserMapper;
import com.codefish.codefish_blog.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author codefish
 * @since 2022-03-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @Override
    public User doLogin(String account, String password) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account", account);
        //根据账户获取账户信息
        User user = this.getOne(wrapper);
        if (user != null) {
            //user不为空，说明账户存在，匹配密码
            if (!passwordEncoder.matches(password, user.getPassword())) {
                //密码校验失败，将待返回的user对象置为null表示失败。
                user = null;
            }
        }
        return user;
    }

    @Override
    public User doRegister(String account, String password) {
        //判断是否有重复用户名
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account", account);
        User hasUser = this.getOne(wrapper);
        if (hasUser != null) {
            //用户名重复了
            return null;
        }
        //创建新用户
        User user = new User();
        user.setAccount(account);
        //密码加密
        String dePassword = passwordEncoder.encode(password);
        user.setPassword(dePassword);
        user.setUsername("code用户" + new Random().nextInt(65535));
        this.save(user);
        return user;
    }
}
